package me.jiatao.taobaotools.utils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.IdRes;
import android.view.View;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import me.jiatao.taobaotools.Constants;

/**
 * Created by JiaTao on 2018/1/24.
 * Email: 535318720@qq.com
 * Version: 1.0
 * Description:
 */

public class ScreenShotUtils {

    private Activity activity;
    private SuccessHandler successHandler;
    private InitHandler initHandler;
    private ScreenShotListener screenShotListener;
    private String imgPath = "";

    public void setScreenShotListener(ScreenShotListener screenShotListener) {
        this.screenShotListener = screenShotListener;
    }

    public ScreenShotUtils(Activity activity) {
        this.activity = activity;
        successHandler = new SuccessHandler();
        initHandler = new InitHandler();
    }

    public void getScreenShot(@IdRes final int resID) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                screenshot(resID);
            }
        }).start();
    }

    private void screenshot(@IdRes int resID) {
        // 获取屏幕
        View dView = activity.findViewById(resID);
        dView.setDrawingCacheEnabled(true);
        dView.buildDrawingCache();
        Bitmap bmp = dView.getDrawingCache();
        if (bmp != null) {
            try {
                File imageDir = new File(Constants.IMAGE_DIR);
                if (!imageDir.exists()) {
                    if (!imageDir.mkdirs()) {
                        initHandler.sendMessage(Message.obtain());
                        return;
                    }
                }

                SimpleDateFormat filesdf = new SimpleDateFormat("yyyy-MM-dd HHmmss"); //文件名不能有：
                String fileTime = filesdf.format(new Date()).toString();//获取系统时间
                String imageName = fileTime + ".png";

                File file = new File(imageDir, imageName);
                imgPath = file.getAbsolutePath();
                try {
                    if (file.exists()) {
                        file.delete();
                    }
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                    initHandler.sendMessage(Message.obtain());
                    return;
                }
                FileOutputStream os = new FileOutputStream(file);
                bmp.compress(Bitmap.CompressFormat.PNG, 100, os);
                os.flush();
                os.close();

                //将截图保存至相册并广播通知系统刷新
                MediaStore.Images.Media.insertImage(activity.getContentResolver(), file.getAbsolutePath(), imageName, null);
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file));
                activity.sendBroadcast(intent);

                successHandler.sendMessage(Message.obtain());

            } catch (Exception e) {
                e.printStackTrace();
                initHandler.sendMessage(Message.obtain());
            }
        } else {
            initHandler.sendMessage(Message.obtain());
            ShowMessageUtils.showInLogCat("Bitmap is null----------------!!!!");
        }

    }

    /**
     * 成功动画handler
     */
    private class SuccessHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            if (screenShotListener != null) {
                screenShotListener.onScreenShotFinish(true, imgPath);
            }
        }
    }

    /**
     * 恢复初始化handler
     */
    private class InitHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            if (screenShotListener != null) {
                screenShotListener.onScreenShotFinish(false, "");
            }

        }
    }


    public interface ScreenShotListener {
        void onScreenShotFinish(boolean isSuccess, String picPath);
    }

}
